package com.lg.atp.sercurity;



import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;



@Component("myDaoAuthticationProvider")
public class MyDaoAuthticationProvider extends AbstractUserDetailsAuthenticationProvider {

	  @Autowired
	  private BCryptPasswordEncoder passwordEncoder;
	  @Autowired
	  private UserDetailService userDetailsService;
	  
	MyDaoAuthticationProvider(){
		super();
	}
	


	@Override
	protected final UserDetails retrieveUser(String userName,
			UsernamePasswordAuthenticationToken arg1)
			throws AuthenticationException {
		UserDetails userDetails = null;
		try {
			userDetails = userDetailsService.loadUserByUsername(userName);
			if (userDetails == null) {
				throw new BadCredentialsException("该用户名不存在！");
			}
			if(!userDetails.isAccountNonLocked())
				throw new LockedException("该用户账户被锁定，请联系管理员");
		} catch (Exception e) {
			throw new BadCredentialsException(e.getMessage());
		}

		return userDetails;
	}


	

	@Override
	protected void additionalAuthenticationChecks(
			UserDetails userDetails,
			UsernamePasswordAuthenticationToken authentication)
			throws AuthenticationException {

		boolean boo = true;
		
		if (StringUtils.isNotEmpty(userDetails.getUsername()))
		{
	      boo = passwordEncoder.matches(authentication.getCredentials().toString(), userDetails.getPassword());
	      if (!boo)
	        throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "用户/密码错误"));
	    }
	}
	
	
	
}
